﻿using Contract;
using Newtonsoft.Json;
using SocketMessaging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using TcpServer.RSA;
using Tool;

namespace TcpServer.SocketCommandImpl
{
    class SendKeySecret : AbstractSocketCommand, ISocketCommand
    {
        private RSACryptoService rSACryptoService;

        public SendKeySecret(ConcurrentDictionary<int, Connection> connectionMap, ConcurrentDictionary<int, Packet> dic)
           : base(connectionMap, dic)
        {
            string privateKey = RSAScrect.PRIVATE_KEY;

            string publicKey = RSAScrect.PUBLIC_KEY;

            rSACryptoService = new RSACryptoService(privateKey, publicKey);
        }

        public void CallCommand(ReceiveData<object> receiveData, Connection connection = null)
        {
            Packet packet;

            // 检查客户端是否存在
            if (!dic.TryGetValue(receiveData.fd, out packet))
            {
                Console.WriteLine("客户端不存在");
                return;
            }

            string secret = receiveData.data as string;

            string resEncrypt = rSACryptoService.Encrypt(secret);

            Connection sendTo;
            bool res = connectionMap.TryGetValue(receiveData.fd, out sendTo);

            if (false == res)
            {
                Console.WriteLine("取出当前连接失败");
                return;
            }

            receiveData.data = resEncrypt;

            sendTo.Send(JsonConvert.SerializeObject(receiveData));

            Console.WriteLine("发送成功：" + receiveData.fd);
        }
    }
}
